/*
*  Copyright 2019-2023 CY
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.ejweixin.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import me.zhengjie.config.FileProperties;
import me.zhengjie.modules.ejweixin.domain.NgAlterationPlan;
import me.zhengjie.modules.ejweixin.domain.NgBrandGuarantee;
import me.zhengjie.utils.DateUtil;
import me.zhengjie.utils.FileUtil;
import lombok.RequiredArgsConstructor;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import me.zhengjie.modules.ejweixin.service.NgAlterationPlanService;
import me.zhengjie.modules.ejweixin.domain.vo.NgAlterationPlanQueryCriteria;
import me.zhengjie.modules.ejweixin.mapper.NgAlterationPlanMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import me.zhengjie.utils.PageUtil;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;

import me.zhengjie.utils.PageResult;

import static me.zhengjie.utils.WordToJpg.convertWordToJpg;

/**
* @description 服务实现
* @author cy
* @date 2025-04-25
**/
@Service
@RequiredArgsConstructor
public class NgAlterationPlanServiceImpl extends ServiceImpl<NgAlterationPlanMapper, NgAlterationPlan> implements NgAlterationPlanService {

    private final NgAlterationPlanMapper ngAlterationPlanMapper;

    private final FileProperties properties;

    @Override
    public PageResult<NgAlterationPlan> queryAll(NgAlterationPlanQueryCriteria criteria, Page<Object> page){
        return PageUtil.toPage(ngAlterationPlanMapper.findAll(criteria, page));
    }

    @Override
    public List<NgAlterationPlan> queryAll(NgAlterationPlanQueryCriteria criteria){
        return ngAlterationPlanMapper.findAll(criteria);
    }

    @Override
    public List<String> getDetail(String id) {
        FileProperties.ElPath path = properties.getPath();
        // 确保上传目录存在
        String uploadDirP = path.getPath().replace("\\","/");
        Path uploadDir = Paths.get(uploadDirP);
        List jpgFileName = new ArrayList<String>();
        NgAlterationPlan vo = ngAlterationPlanMapper.selectById(id);
        ngAlterationPlanMapper.updateViewCount(id);
        if(null != vo.getType() && vo.getType().equals("3")){
            jpgFileName.add(vo.getVideoPath());
            return jpgFileName;
        }else{
            String filePath = vo.getDetailsTxt();
            File folder = new File(uploadDir + "/" + filePath);
            if (folder.exists() && folder.isDirectory()) {
                String[] fileNames = folder.list(); // 获取所有文件和子目录的名称
                Arrays.sort(fileNames, (s1, s2) -> {
                    int num1 = Integer.parseInt(s1.replaceAll("\\D+", ""));
                    int num2 = Integer.parseInt(s2.replaceAll("\\D+", ""));
                    return Integer.compare(num1, num2);
                });

                for (String fileName : fileNames) {
                    jpgFileName.add(filePath + "/" + fileName);
                }
            } else {
                System.out.println("文件夹不存在或路径不是目录！");
            }
        }

        return jpgFileName;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void create(NgAlterationPlan resources) throws Exception {
        try {
            FileProperties.ElPath path = properties.getPath();
            // 确保上传目录存在
            String uploadDirP = path.getPath().replace("\\","/");
            Path uploadDir = Paths.get(uploadDirP);
            String wordFile = resources.getDetailsTxt();
            if(null != wordFile && !wordFile.equals("")){
                String savePath = "wordJpg_" + UUID.randomUUID();
                convertWordToJpg(uploadDir + "/" + wordFile, uploadDir + "/" + savePath);
                resources.setDetailsTxt(savePath);
            }
            resources.setCreateTime(DateUtil.getTimeStamp());
            save(resources);
        }catch (Exception e){
            e.printStackTrace();
        }

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(NgAlterationPlan resources) {
        NgAlterationPlan ngAlterationPlan = getById(resources.getId());
        try {
            if (resources.getDetailsTxt() != null && !resources.getDetailsTxt().isEmpty()) {
                String lowerCasePath = resources.getDetailsTxt();
                if(lowerCasePath.endsWith(".doc") ||
                        lowerCasePath.endsWith(".docx") ||
                        lowerCasePath.endsWith(".docm")){
                    FileProperties.ElPath path = properties.getPath();
                    // 确保上传目录存在
                    String uploadDirP = path.getPath().replace("\\","/");
                    Path uploadDir = Paths.get(uploadDirP);
                    String wordFile = resources.getDetailsTxt();
                    if(null != wordFile && !wordFile.equals("")){
                        String savePath = "wordJpg_" + UUID.randomUUID();
                        convertWordToJpg(uploadDir + "/" + wordFile, uploadDir + "/" + savePath);
                        resources.setDetailsTxt(savePath);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ngAlterationPlan.copy(resources);
        saveOrUpdate(ngAlterationPlan);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(List<Integer> ids) {
        removeBatchByIds(ids);
    }

    @Override
    public void download(List<NgAlterationPlan> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (NgAlterationPlan ngAlterationPlan : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("数据类型1装修攻略2实景作品3工地现场", ngAlterationPlan.getType());
            map.put("标题", ngAlterationPlan.getTitle());
            map.put("缩略图地址", ngAlterationPlan.getImgPath());
            map.put("浏览次数", ngAlterationPlan.getViewsCount());
            map.put("文章html", ngAlterationPlan.getDetailsTxt());
            map.put("创建者", ngAlterationPlan.getCreateBy());
            map.put("更新者", ngAlterationPlan.getUpdateBy());
            map.put("创建日期", ngAlterationPlan.getCreateTime());
            map.put("更新时间", ngAlterationPlan.getUpdateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}